<template>
  <div class="comp__report_detail">
    <top-header ref="refHeader" @change="searchChange" :event-list="nodes" @pro-change="proChange"/>
    <div class="echar__container">
      <h3>事件趋势</h3>
      <e-charts ref="chart" :options="options" autoresize @legendselectchanged="legendchanged"/>
    </div>
    <div class="events__list">
      <h3>
        <span>事件统计明细</span>
        <el-button type="primary" size="mini" @click="exportToExcel">导出</el-button>
      </h3>
      <el-table :data="list" row-key="button_id" border default-expand-all >
        <el-table-column prop="date" label="日期"></el-table-column>
        <el-table-column prop="click_times" label="点击次数" align="center"></el-table-column>
        <el-table-column prop="click_users" label="点击人数" align="center"></el-table-column>
        <el-table-column label="次数/人数" align="center">
          <template slot-scope="scope">
            {{ formatPerUser(scope.row) }}
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import ECharts from '@/components/Echarts'
import * as echarts from 'echarts/core'
import { LineChart } from 'echarts/charts'
import { utils, write } from 'xlsx'
import { getButtonEventDetailApi, getButtnEventListApi } from '@/api/report/button-events'
import TopHeader from './header.vue'
import { parseTime } from '@/utils/index'

echarts.use([LineChart])

export default {
  data () {
    return {
      title: '',
      list: [],
      show: false,
      selectLegend: ['点击次数', '点击人数'],
      openParams: {},
      nodes: [],
      options: null
    }
  },
  components: {
    ECharts,
    TopHeader
  },
  methods: {
    legendchanged (params) {
      const item = params.name
      console.log(item)
    },
    getChartOption (list) {
      const tooltip = {
        trigger: 'axis'
      }
      const legend = {
        bottom: 0,
        type: 'scroll',
        icon: 'circle',
        data: this.selectLegend
      }
      const grid = {
        left: '4%',
        right: '4%',
        bottom: '10%',
        containLabel: true
      }
      const xAxis = {
        type: 'category',
        boundaryGap: false,
        data: list.map(v => v.date),
        axisLabel: {
          interval: list.length > 15 ? 1 : 0 // 显示所有刻度

        }
      }
      const yAxis = this.selectLegend.map((v, i) => {
        return {
          id: i,
          type: 'value',
          name: v,
          axisLabel: {
            // y轴上带的单位
            formatter: '{value}'
          },
          // 轴线
          axisLine: {
            show: true
          },
          // 分割线
          splitLine: {
            show: false
          },
          position: i === 0 ? 'left' : 'right'
        }
      })
      const clickTimes = []
      const clickUsers = []
      list.forEach(v => {
        clickTimes.push(v.click_times)
        clickUsers.push(v.click_users)
      })
      const series = [
        { type: 'line', name: '点击次数', data: clickTimes, yAxisIndex: 0 },
        { type: 'line',
          name: '点击人数',
          data: clickUsers,
          yAxisIndex: 1
        }
      ]
      return {
        tooltip,
        legend,
        grid,
        xAxis,
        yAxis,
        series
      }
    },
    init (list) {
      this.options = this.getChartOption(list)
      this.list = list
    },
    formatPerUser (item) {
      if (item.click_users === 0) return '-'
      return (item.click_times / item.click_users).toFixed(2)
    },
    searchChange (params) {
      this.openParams = params
      this.getDetail()
    },
    async getDetail () {
      const [date_begin = '', date_end = ''] = this.openParams.date
      const params = {
        appid: this.openParams.appid,
        version: this.openParams.version,
        unionid: this.openParams.unionid,
        date_begin,
        date_end,
        button_id: this.openParams.button_id
      }
      const data = await getButtonEventDetailApi(params)

      if (data.code === 200) {
        this.init(data.data || [])
      } else {
        this.$message.error(data.msg)
      }
    },
    exportToExcel () {
      if (this.list.length === 0) {
        this.$message.warning('暂无数据导出')
        return
      }
      const button_id = this.openParams.button_id
      const button_name = this.nodes.find((v) => v.button_id === button_id)?.button_name || ''
      const data = [
        ['事件ID', '事件名称', '日期', '点击次数', '点击人数', '次数/人数']
      ]
      this.list.forEach(v => {
        data.push([button_id, button_name, v.date, v.click_times, v.click_users, this.formatPerUser(v)])
      })
      const wb = utils.book_new()
      const ws = utils.aoa_to_sheet(data)
      utils.book_append_sheet(wb, ws, this.title)
      const wsout = write(wb, { bookType: 'xlsx', type: 'array' })

      const blob = new Blob([wsout], { type: 'application/octet-stream' })
      // 创建下载链接并模拟点击
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `${button_id}-${button_name}事件详情.xlsx`
      document.body.appendChild(a)
      a.click()

      // 清理
      setTimeout(() => {
        document.body.removeChild(a)
        window.URL.revokeObjectURL(url)
      }, 0)
    },
    async proChange (params) {
      this.openParams = params
      await this.initNodesData()
      const button_id = this.nodes[0]?.button_id
      if (!button_id) {
        this.list = []
        this.init([])
        return
      }
      this.openParams.button_id = button_id
      this.$refs.refHeader.setQueryParams({ button_id: button_id })

      this.getDetail()
    },
    formatListDataInit (list) {
      const values = []
      const allNodes = []
      let maxId = 0
      function recursion (arr, parent, parentId) {
        for (let i = 0; i < arr.length; i++) {
          const item = arr[i]
          const children = []
          const btn = { ...item.ButtonInfo, children, parent_id: parentId }
          parent.push(btn)
          allNodes.push({ ...item.ButtonInfo })
          maxId = Math.max(maxId, item.ButtonInfo.button_id)
          if (item.Children) recursion(item.Children, children, btn.button_id)
        }
      }
      recursion(list, values, null)
      return { values, allNodes, maxId }
    },
    async initNodesData () {
      const params = {
        ...this.openParams,
        version: '',
        date: parseTime(Date.now(), '{y}-{m}-{d}'),
        mode: 1,
        button_id: ''
      }
      const data = await getButtnEventListApi(params)
      const { allNodes } = this.formatListDataInit(data.data || [])
      this.nodes = allNodes
    }
  },
  mounted () {
    this.initNodesData()
  }
}
</script>

<style lang="scss" scoped>
.comp__report_detail {

}
h3 {
    font-size: 16px;
    font-weight: bold;
  }
.echar__container {
  height: 300px;

}
.events__list {
  padding: 20px 0;
  h3 {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 10px;
  }
}

.actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 10px;;
  margin-bottom: 20px;
  /deep/ .el-tag--info {
    display: flex;
    align-items: center;

  }
  /deep/ .el-select__tags-text {
    max-width: 80px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}
.actions__item {
  display: flex;
  align-items: center;
  gap: 10px;
}
</style>
